import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store  from '../store'
import Basic from '../components/layout/Basic.vue'
import { info } from '@/api/user'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue'),
    meta: {
      group: '',
      showName: '登录',
    }
  },
  {
    path: '/',
    component: Basic,
    children: [
      {
        path: '',
        component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue'),
        name: 'Home',
        meta: {
          group: '',
          showName: '首页',
        },
      },
      {
        path: '/permissions/add',
        name: 'PermissionAdd',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "PermissionAdd" */ '../views/About.vue'),
        meta: {
          group: '',
          showName: '添加权限',
        }
      },
      {
        path: '/permissions',
        name: 'PermissionList',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "PermissionList" */ '../views/PermissionList.vue'),
        meta: {
          group: '',
          showName: '权限列表',
        }
      },
      // ---------- 用户相关 start -----------------
      {
        path: '/users',
        name: 'UserList',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "PermissionList" */ '../views/UserList.vue'),
        meta: {
          group: '',
          showName: '用户列表',
        }
      },
      // ---------- 用户相关 end -----------------
    ],
  },
  { 
    path: '/:pathMatch(.*)*', 
    name: 'NotFound', 
    component: () => import(/* webpackChunkName: "notfound" */ '../views/NotFound.vue'),
    meta: {
      group: '',
      showName: '404 Not Found',
    }
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 不需要跳转到登录页面的路由数组
const doNotLoginRouterNameArr = ['Login']
const doNotAddTabRouterNameArr = ['Login']

router.beforeEach(async (to, from) => {
  console.log('router to', to)
  console.log('router from', from)
  let authorizationData = store.state.authorizationData
  console.log("authorizationData", authorizationData)
  if (authorizationData === '') {
    // 如果 token 信息等于空，要就从 localstorage 获取一下
    const localAuthorizationData = localStorage.getItem('authorizationData')
    console.log('localAuthorizationData',  localAuthorizationData)
    if (localAuthorizationData !== null && localAuthorizationData !== '') {
      store.dispatch('setAuthorizationData', localAuthorizationData)
      // 在这边需要获取一下用户信息，因为 store 里面没有用户信息
      try {
        const getInfoResponse = await info()
        const getInfoResponseData = getInfoResponse.data
        // 获取成功了
        store.dispatch('setLoginUserInfo', getInfoResponseData.Data)
        // 再次保存 jwt token 到 localstorage
        authorizationData = localAuthorizationData
      } catch (error) {
        console.log("router get info error", error)
        // 获取用户信息失败了 清空本地 jwt 相关信息
        localStorage.removeItem('authorizationData')
      }
    }
  }

  if (authorizationData === '' && doNotLoginRouterNameArr.indexOf(String(to.name)) === -1) {
    // 如果 jwt 信息为空 并且是需要登录的路由，就跳转到登录
    // 保存一下 to，用来进行登陆后的跳转
    if (doNotLoginRouterNameArr.indexOf(String(to.name)) === -1) {
      store.commit('setLoginRedirectionRoute', to)
    }
    return { name: 'Login'}
  }

  if (authorizationData !== '' && doNotLoginRouterNameArr.indexOf(String(to.name)) !== -1) {
    // 如果 jwt 信息不为空 并且不是需要登录的路由，就跳转到首页
    if (from.name === undefined) {
      return { name: 'Home'}
    } else {
      return from
    }
  }
  // 刷新页面以及跳转的时候切换高亮菜单标签
  if (doNotAddTabRouterNameArr.indexOf(String(to.name)) === -1) {
    store.commit('changeOpenMenu', {
      menu: to.name,
      group: '',
    })
    // 查看是否打开了此 tab
    const tabIndex = store.state.openTabs.find((tab) => tab.key === to.fullPath)
    console.log('tabIndex', tabIndex)
    if (tabIndex === undefined) {
      // 增加 tab 
      store.commit("addTab", {
        title:to.meta.showName,
        key: to.fullPath,
        routeName: to.name,
        routeParams: to.params
      })
    } else {
      // 高亮开启的tab
      store.commit('changeActiveTab', to.fullPath)
    }
  }
})

export default router
